package plugin.eos.awake.flutter.awake1.network;

import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.CipherSuite;
import okhttp3.ConnectionSpec;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.TlsVersion;
import okhttp3.logging.HttpLoggingInterceptor;
import plugin.eos.awake.flutter.awake1.BuildConfig;
import plugin.eos.awake.flutter.awake1.utils.LogUtils;
import plugin.eos.awake.flutter.awake1.utils.Utils;

/**
 * Creation time: 2018/7/30
 * Editor: $USER_NAME
 * Functional description:
 */
class NetworkFactory {

    private static final int DISK_CACHE_SIZE = 50 * 1024 * 1024;

    private static final String HTTP_USER_AGENT = "User-Agent";

    private static OkHttpClient okHttpClient;

    private static OkHttpClient createOkHttpClient() {
        OkHttpClient okHttpClient;
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(message -> {
            if (!message.startsWith("server:") && !message.startsWith("date:")
                    && !message.startsWith("Server:") && !message.startsWith("Date:")
                    && !message.startsWith("Connection:") && !message.startsWith("X-Powered-By:")
                    && !message.startsWith("content-type:") && !message.startsWith("content-length:")
                    && !message.startsWith("Access-Control-Allow-Origin: *") && !message.startsWith("Access-Control-Allow-Headers: Content-Type")
                    && !message.startsWith("Content-type: application/json") && !message.isEmpty()
                    && !message.startsWith("--> END POST") && !message.startsWith("<-- END HTTP")
                    && !message.startsWith("access-control-allow-headers:") && !message.startsWith("access-control-allow-origin:")) {
                LogUtils.d("GsonRequst", "GsonRequst = " + message);
            }
//            Logger.json(message);
        });
        loggingInterceptor.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);

        //insert essential headers into APIS
        Interceptor headers = chain -> {
            Request oldRequest = chain.request();
            Request newRequest;

            Request.Builder newBuilder = oldRequest.newBuilder();
            newBuilder.addHeader(HTTP_USER_AGENT, Utils.getUserAgent(null));

            newRequest = newBuilder.build();
            return chain.proceed(newRequest);
        };

        ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                .tlsVersions(TlsVersion.TLS_1_1)
                .tlsVersions(TlsVersion.TLS_1_2)
                .cipherSuites(
                        CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
                        CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
                        CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256)
                .build();

        okHttpClient = new OkHttpClient.Builder()
//				.cache(cache)
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
//				.addInterceptor(headers)
                .addInterceptor(loggingInterceptor)
                .addInterceptor(CommonParamsInterceptor.getInstance())
                .sslSocketFactory(createSSLSocketFactory())
                .hostnameVerifier((hostname, session) -> true)
                .build();
        return okHttpClient;
    }


    public static class TrustAllCerts implements X509TrustManager {

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) {

        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) {

        }

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[0];
        }
    }


    private  static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());

            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }
        return ssfFactory;
    }
    static OkHttpClient getOkHttpClient() {
        if (null == okHttpClient) {
            okHttpClient = createOkHttpClient();
        }
        return okHttpClient;
    }
}

